<?php
/**
 * CarSale
 *  
 * @author x
 * @version 
 */

class Model_CarSale extends Zend_Db_Table_Abstract
{
    /**
     * The default table name
     */
    protected $_name = 'tcl_car_sale';

    public function setSalePost($data){
        
        //$data = array('title'=>'title');
        //$id = $this->insert($data);
        try {
			$id = $this->insert($data);
        } catch(Exception $e) {
        	// when it fails to insert
        	// how can i run this echo
        	echo $e; //??
        	exit();
        }
        return $id;
    }
    
    //更新卖 车信息
    public function setSaleUpdate($data, $id, $uid) {
        
        $db = $this->getAdapter();
        $where = $db->quoteInto('id = ?', $id)
        		.$db->quoteInto('AND uid = ?', $uid);
        try {
			$row = $this->update($data, $where);
        } catch(Exception $e) {
        	// when it fails to insert
        	// how can i run this echo
        	echo $e; //??
        	exit();
        }
        return $row;
    }
    
    
    //取列表
    public function getList($page, $url, $city_id, $brand_id, $model_id, $low_price, $high_price, $low_age, $high_age, $is_pic, $on_sale, $query, $type, $order, $count=20) {
        
        $core = new Model_Core();
        
        $db = $this->getAdapter();
        $select = $db->select();
        
        $select->from($this->_name, array('id','title','note','province_id','city_id','brand_id','model_id','name_id','kilometer','price','car_year','uid','car_month', 'session_id','car_img','img_dir','img_arr','company_id','is_app','created_at','color_name'));

        //use join here

        
        //is_app 正常通过审核给予显示
        $select->where("is_app = 1 || is_app = 2");
        
        
        if ($city_id != '-1' && $city_id){
        	$select->where('province_id = ? OR city_id = ?', $city_id);
        }
        
        if ($brand_id){
            $select->where('brand_id = ?', $brand_id);
        }
        if ($model_id){
            $select->where('model_id = ?', $model_id);
        }
        if ($low_price){
            $select->where('price >= ?', $low_price);
        }
        if ($high_price){
            $select->where('price <= ?', $high_price);
        }
        //现在的年份-上牌年份=车龄
        $year = date('Y');
        if ($low_age){
            $select->where("car_year <= ?", $year - $low_age);
        }
        if ($high_age){
            $select->where("car_year >= ?", $year - $high_age);
        }
        if ($query) {
            $select->where("title like ? OR note like ? OR price like ? OR contact_user like ? OR car_year like ? OR id like ? OR uid like ?", "%$query%");
        }
        
        //类型
        if ($type == 2) {
            $select->where("company_id != ?", 0);
        }
        if ($type == 1) {
            $select->where("company_id = ?", 0);
        }
        
        //在售 有图
        if ($is_pic){
            $select->where("img_arr != ?", "");
        }
        //IS_APP = 1 销售中
        if ($on_sale){
            $select->where("is_app = ?", 1);
        }
        
        
        //排序
        switch ($order) {
            //DEFAULT 为智能排序 ****需修改
            case 'default':
                $select->order(array('is_app','created_at DESC'));
                break;
            //时间倒序
            case 'new':
                $select->order("created_at DESC");
                break;
            //车价正序
            case 'price':
                $select->order("price");
                break;
            //里程正序
            case 'kilometer':
                $select->order("kilometer");
                break;
            //车龄倒序，月份倒序
            case 'age':
                $select->order(array('car_year DESC','car_month DESC'));
                break;
            default:
                $select->order("created_at DESC");
                break;
        }
        
       
        //exit();
        $how = count($db->fetchAll($select));
        //echo $how;
        //print_r($db->fetchAll($select));
        
        $howpage = ceil($how / $count);
        $offset	 = $page * $count - $count;

        $multipage = $core->html_multi($page, $howpage, $url);
		
        $select->limit($count, $offset);
        
        try {
            $row = $db->fetchAll($select);
        } catch (Exception $e) {
            echo $e;
            exit();
        }
        
        //print_r ($row);
        
        $lowhow = 0;
        //当前选项车源较少 需要推荐其他车源
        if ($how < $count){
            $is_row = $db->fetchCol($select);
            
            $lowhow = $how;
            $select = "";
            $select = $db->select();
            $select->from($this->_name, array('id','title','note','province_id','city_id','brand_id','model_id','name_id','kilometer','price','car_year','uid','car_month', 'session_id','car_img', 'img_dir','company_id','is_app','created_at','color_name'));
            $select->where("is_app = 1");
            //$select->where("id IN ?", $is_row);
            for ($i = 0;$i < $how; $i++){
                $select->where("id != ?", $is_row[$i]);
            }
            $select->order("RAND()");
            $select->limit(15);
            
            try {
            	$newrow = $db->fetchAll($select);
            } catch (Exception $e) {
            	echo $e;
            	exit();
            }

            $row = array_merge($row, $newrow);
        }

        //echo $select->__toString();
        //
        $i = 0;
        foreach ($row as $value){
            $row[$i][show_note] = $core->cutstr($value[note], 70);
            $price_arr = explode('.', $value[price]);
            $row[$i][show_price] = $price_arr[0].".<small>".$price_arr[1]."</small>";
            //print_r($price_arr);
            $i++;
        }
        
        //ROW 数据组 MULITPAGE 分页 HOW总条数
        $results = array(
            'row' => $row,
            'mulitpage' => $multipage,
            'how' => $how,
        	'lowhow' => $lowhow
        );
        
        return $results;
    }
    
    //取列表BY SET
    public function getListOnSet($page, $url, $app, $query, $uid, $count=20) {
        //取列表        
        	$core = new Model_Core();
        
        	$db = $this->getAdapter();
        	$select = $db->select();
        
        	$select->from($this->_name, array('id','title','province_id','city_id','session_id','car_img','img_dir','company_id','is_app','view','created_at'));
        
        	//use join here
        
        
        	//is_app 正常通过审核给予显示
        	//$select->where("is_app = 1");
        	if ($uid){
        	    $select->where("uid = $uid");
        	}
        	
        
        	if ($query) {
        		$select->where("title like ? OR id like ?", "%$query%");
        	}
        
        	//TYPE = 1 销售中  、= 2 售出
        	if ($app != '-1'){
        		$select->where("is_app = ?", $app);
        	}
        
        	$select->order("created_at DESC");
        
        
        	 
        	//exit();
        	$how = count($db->fetchAll($select));
        	//echo $how;
        	//print_r($db->fetchAll($select));
        
        	$howpage = ceil($how / $count);
        	$offset	 = $page * $count - $count;
        
        	$multipage = $core->html_multi($page, $howpage, $url);
        
        	$select->limit($count, $offset);
        
        	try {
        		$row = $db->fetchAll($select);
        	} catch (Exception $e) {
        		echo $e;
        		exit();
        	}
        
        	//print_r ($row);
        
        
        
        	//echo $select->__toString();
        	//
        
        					//ROW 数据组 MULITPAGE 分页 HOW总条数
        			$results = array(
        			'row' => $row,
        			'mulitpage' => $multipage,
        			'how' => $how,
        			'lowhow' => $lowhow
        			);
        
        			return $results;

    }
    
    
    //SAME PRICE SAME BRAND
    public function getSameList($city_id, $brand_id, $low_price, $high_price, $count=5) {
        
        $db = $this->getAdapter();
        $select = $db->select();
        
        $select->from($this->_name, array('id','title','price', 'session_id','car_img','img_dir','is_app','province_id','city_id','brand_id','price','created_at'));
        
        //is_app 正常通过审核给予显示
        $select->where("is_app = 1");
        
        
        if ($city_id != '-1' && $city_id){
        	$select->where('province_id = ? OR city_id = ?', $city_id);
        }
        
        if ($brand_id){
        	$select->where('brand_id = ?', $brand_id);
        }
        if ($low_price){
        	$select->where('price >= ?', $low_price);
        }
        if ($high_price){
        	$select->where('price <= ?', $high_price);
        }
        
        $select->order('created_at DESC')
        		->limit($count);
        
        //echo $select->__toString();
        //exit();
        
        try {
            $row = $db->fetchAll($select);
        } catch (Exception $e) {
            echo $e;
            exit();
        }
        
        
        return $row;
    }

    //车辆详细信息
    public function getView($cid) {
    	
        $db = $this->getAdapter();
        $select = $db->select();
        //$where = $db->quoteInto('id = ?', "$cid");
        
        
        $select->from(array('t1'=>$this->_name), array('id','title','note','province_id','city_id','model_id','name_id','contact_user','uid','kilometer','price','car_year','car_month','safe_year','safe_month','check_year','check_month','car_operate','maintenance', 'session_id','car_img', 'img_dir', 'img_arr','company_id','is_app','view','created_at','color_value','color_name'))
        		->from(array('t2'=>'tcl_car_model'), array('id','brand','brand_icon','model','newprice','kind','pailiang','biansuxiang'));
        
        $select->where('t1.name_id = t2.id OR t1.model_id = t2.id')
        		->where('t1.id = ?', $cid);
        //$select->join('bar', 'foo.id = bar.id', '*');
        
        //echo $select->__toString();
        //exit();
		
        try {
            $row = $db->fetchRow($select);
        } catch (Exception $e) {
            echo $e;
            exit();
        }
        
        return $row;
    }
    
    //对比车辆详细信息 USED IN(CIDS)
    public function getContrastView($cids) {
    	 
        $db = $this->getAdapter();
        //$select = $db->select();
        try {
            $row = $this->find($cids)->toArray();
        } catch (Exception $e) {
            echo $e;
            exit();
        }
        
        return $row;
    }
    
    public function getViewName($cid) {
        
        $db = $this->getAdapter();
        //$select = $db->select();
        try {
            $row = $this->find($cid)->toArray();
        } catch (Exception $e) {
            echo $e;
            exit();
        }
        
        return $row;
    }
    
    //删除车源信息
    public function setSaleDel($ids, $uid) {
    	
        $db = $this->getAdapter();
        
        $set = array(
        	'is_app'   => 3,
        );
        $ids = explode(',', $ids);
        
        $where = $db->quoteInto('id IN (?)', $ids)
        		.$db->quoteInto("AND uid = ?", $uid);
        
        try {
        	$row = $this->update($set, $where);
        } catch (Exception $e) {
        	echo $e;
        	exit();
        }
        
        
        return $row;
    }
    
    //售出车源
    public function setSaleSale($ids, $uid) {
    	 
    	$db = $this->getAdapter();
    
    	$set = array(
    			'is_app'   => 2,
    	);
    	$ids = explode(',', $ids);
    
    	$where = $db->quoteInto('id IN (?)', $ids)
    	.$db->quoteInto("AND uid = ?", $uid);
    
    	try {
    		$row = $this->update($set, $where);
    	} catch (Exception $e) {
    		echo $e;
    		exit();
    	}
    	return $row;
    }
    
    //审核
    public function setSaleAudit($ids) {
    	$db = $this->getAdapter();
    
    	$set = array(
    		'is_app'   => 4,
    	);
    	$ids = explode(',', $ids);
    
    	$where = $db->quoteInto('id IN (?)', $ids);
    
    	try {
    		$row = $this->update($set, $where);
    	} catch (Exception $e) {
    		echo $e;
    		exit();
    	}
    	/*
    	$msg = new Model_CommonMsg();
    	$msg->setMsgTo($to_uid, "您发布的信息因违反淘车乐用户协议被管理员删除", "您发布的信息编号为 $ids 因违反淘车乐用户协议被管理员删除了, 他们被移到您的管理中心 - 我的发布 - 审核中的信息中。淘车乐拒绝广告形式的信息发布！");
    	*/
    	
    	return $row;
    }
    
    //恢复显示
    public function setRestore($id, $uid) {
    
    	$db = $this->getAdapter();
    
    	$set = array(
    			'is_app'   => 1,
    	);
    
    	$where = $db->quoteInto('id = ?', $id)
    	.$db->quoteInto("AND uid = ?", $uid);
    
    	try {
    		$row = $this->update($set, $where);
    	} catch (Exception $e) {
    		echo $e;
    		exit();
    	}
    	return $row;
    }
    
    
    //刷新车源
    public function setRefresh($id, $uid) {
    
    	$db = $this->getAdapter();
    
    	$set = array(
    		'created_at'   => time(),
    	);
    
    	$where = $db->quoteInto('id = ?', $id)
    			.$db->quoteInto("AND uid = ?", $uid);
    
    	try {
    		$row = $this->update($set, $where);
    	} catch (Exception $e) {
    		echo $e;
    		exit();
    	}
    	return $row;
    }
    
    //PROFIT
    public function getProfitCars($city_id="-1", $query="", $count=6) {
        $db = $this->getAdapter();
        $select = $db->select();
        
        $select->from($this->_name, array('id','title','price', 'session_id','car_img','img_dir','is_app','province_id','city_id','brand_id','price','created_at'));
        
        //is_app 在售
        $select->where("is_app = 1");
 
        if ($city_id != '-1'){
            $select->where('province_id = ? OR city_id = ?', $city_id);
        }
       
		//PROFIT 排序
        $select->order('RAND()')
        		->limit($count);
        
        //echo $select->__toString();
        //exit();
        
        try {
        	$row = $db->fetchAll($select);
        } catch (Exception $e) {
        	echo $e;
        	exit();
        }
        
        
        return $row;
        
    }
    
    
    //浏览数 +1
    public function setViews($cid) {
        
        $db = $this->getAdapter();
        
        $data = array (
        	'view'	=> new Zend_Db_Expr('view + 1'),//字段自增1
        );
        
        $where = $db->quoteInto('id = ?', $cid);
        
        try {
        	$id = $this->update($data, $where);
        } catch(Exception $e) {
        	// when it fails to insert
        	// how can i run this echo
        	echo $e; //??
        	exit();
        }
        return $id;

    }
    
    

    
}
